package com.haotunet.app.goldtreasure.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.BuyConfirmModel;
import com.haotunet.app.goldtreasure.model.BuyGoldDetail;
import com.haotunet.app.goldtreasure.model.GoldInfo;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.utils.Utils;
import com.haotunet.app.goldtreasure.views.TitleView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class BuyGoldActivity extends BaseActivity {
    @InjectView(R.id.title_view)
    TitleView titleView;
    @InjectView(R.id.txt_current_gold_price)
    TextView txtCurrentGoldPrice;
    @InjectView(R.id.tv_follow_grams)
    TextView tvFollowGrams;
    @InjectView(R.id.tv_follow_amount)
    TextView tvFollowAmount;
    @InjectView(R.id.iv_gram_line)
    ImageView ivGramLine;
    @InjectView(R.id.iv_amount_line)
    ImageView ivAmountLine;
    @InjectView(R.id.buy_way_switch_layout)
    LinearLayout buyWaySwitchLayput;
    @InjectView(R.id.et_buy_gram)
    EditText etBuyGram;
    @InjectView(R.id.tv_estimated_amount)
    TextView tvEstimatedAmount;
    @InjectView(R.id.follow_gram_layout)
    LinearLayout followGramLayout;
    @InjectView(R.id.et_buy_amount)
    EditText etBuyAmount;
    @InjectView(R.id.follow_amount_layout)
    LinearLayout followAmountLayout;
    @InjectView(R.id.tv_estimated_gram)
    TextView tvEstimatedGram;
    @InjectView(R.id.product_detail_layout)
    LinearLayout productDetailLayout;
    @InjectView(R.id.tip_content)
    TextView tipContent;
    @InjectView(R.id.tip_layout)
    LinearLayout tipLayout;
    @InjectView(R.id.btn_pay)
    Button btnPay;
    private final int GET_GOLD_PRICE_SUCCESS = 1;
    private final int CONFIRM_CHOOSE_SUCCESS = 2;
    @InjectView(R.id.txt_product_rate)
    TextView txtProductRate;
    @InjectView(R.id.tv_interest_date)
    TextView tvInterestDate;
    private String gold_price;
    private String buyType;
    private String regularId;
    private String buyGrams;
    private String buyAmount;
    private int productFlag;
    private int productType;
    private boolean followAmount = false;

    private Handler handle = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GET_GOLD_PRICE_SUCCESS:
                    GoldInfo info = (GoldInfo) msg.obj;
                    gold_price = info.getCurrentGoldPrice();
                    txtCurrentGoldPrice.setText(gold_price);
                    break;

                case CONFIRM_CHOOSE_SUCCESS:
                    BuyConfirmModel model = (BuyConfirmModel) msg.obj;
                    ActivityUtils.gotoGoldOrder(BuyGoldActivity.this, model, buyType, regularId, productFlag);
                    break;
                default:
                    break;
            }
        }

    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buy_gold);
        ButterKnife.inject(this);
        initView();
        initData();
        getBuyGoldDetail();
    }

    private void initData() {
        getGoldPrice();
    }

    private void getBuyGoldDetail() {
        ActionUtil actionUtil = new ActionUtil(BuyGoldActivity.this);
        actionUtil.getBuyGoldDetail(getIntent().getStringExtra("regularId"));
        actionUtil.setOnPassBackListener(new OnPassBackListener() {
            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()){
                    return;
                }
                BuyGoldDetail buyGoldDetail = (BuyGoldDetail) model;
                if (buyGoldDetail == null) {
                    UIHelper.showToast(BuyGoldActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (buyGoldDetail.getErrorMsg() != null) {

                    UIHelper.showToast(BuyGoldActivity.this, buyGoldDetail.getErrorMsg());

                } else {
                    etBuyGram.setHint(buyGoldDetail.getByGramPlaceholder());
                    etBuyAmount.setHint(buyGoldDetail.getByMoneyPlaceholder());
                    if (productType == 5) {
                        tvEstimatedGram.setText(buyGoldDetail.getGoldQuantity());
                        etBuyAmount.setText(buyGoldDetail.getGoldMoney());
                        tipContent.setText(buyGoldDetail.getTips());
                    }
                    if (buyGoldDetail.getShowYearRate()) {
                        productDetailLayout.setVisibility(View.VISIBLE);
                        txtProductRate.setText(buyGoldDetail.getYearRate());
                        tvInterestDate.setText(buyGoldDetail.getIncomeBeginTime());
                    }
                }
            }
        });
    }

    private void getGoldPrice() {
        ActionUtil actionUtil = new ActionUtil(this);
        actionUtil.getCurrentGoldPrice();
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()){
                    return;
                }
                GoldInfo info = (GoldInfo) model;
                if (info == null) {
                    UIHelper.showToast(BuyGoldActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (info.getErrorMsg() != null) {

                    UIHelper.showToast(BuyGoldActivity.this, info.getErrorMsg());

                } else {
                    Message msg = new Message();
                    msg.what = GET_GOLD_PRICE_SUCCESS;
                    msg.obj = info;
                    handle.sendMessage(msg);
                }
            }
        });
    }

    private void initView() {
        buttonInvalid();
        productFlag = getIntent().getIntExtra("productFlag", 0);
        String productName = getIntent().getStringExtra("productName");
        productType = getIntent().getIntExtra("productType", 0);
        regularId = getIntent().getStringExtra("regularId");
        titleView.getTitletextView().setVisibility(View.VISIBLE);
        titleView.getTitletextView().setText(productName);
        titleView.getBackView().setVisibility(View.VISIBLE);
        if (0 == productFlag) {
            buyWaySwitchLayput.setVisibility(View.GONE);
        }
        addEditextListener();
        setExperienceGoldView();
        tvFollowGrams.setSelected(true);
    }


    /*设置万元体验金的视图*/
    private void setExperienceGoldView() {
        if (5 == productType) {
            tipLayout.setVisibility(View.VISIBLE);
            followGramLayout.setVisibility(View.GONE);
            followAmountLayout.setVisibility(View.VISIBLE);
            etBuyAmount.setFocusable(false);
            followAmount = true;
        }
    }

    private void addEditextListener() {
        etBuyGram.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String inputString = s.toString();
                if (inputString.contains(".")) {
                    if (inputString.length() - 1 - inputString.toString().indexOf(".") > 3) {
                        inputString = (String) inputString.subSequence(0, inputString.indexOf(".") + 4);
                        etBuyGram.setText(inputString);
                        etBuyGram.setSelection(inputString.length());
                    }
                }
                if (inputString.trim().substring(0).equals(".") || inputString.trim().substring(0).equals("0")) {
                    inputString = "";
                    etBuyGram.setText(inputString);
                    etBuyGram.setSelection(0);
                }
                if (inputString.length() == 0) {
                    tvEstimatedAmount.setText("0.00");
                    buttonInvalid();
                } else {
                    buttonEffective();
                    double inputGram = Double.parseDouble(inputString.toString().trim());
                    if (!TextUtils.isEmpty(gold_price)) {
                        double goldPrice = Double.parseDouble(gold_price.toString());
                        tvEstimatedAmount.setText(Utils.decimalMultiplyKeepTwoPlaces(inputGram, goldPrice));
                    }
                }
            }
        });

        etBuyAmount.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String inputString = s.toString();
                if (inputString.contains(".")) {
                    if (inputString.length() - 1 - inputString.toString().indexOf(".") > 2) {
                        inputString = (String) inputString.subSequence(0, inputString.indexOf(".") + 3);
                        etBuyAmount.setText(inputString);
                        etBuyAmount.setSelection(inputString.length());
                    }
                }
                if (inputString.trim().substring(0).equals(".") || inputString.trim().substring(0).equals("0")) {
                    inputString = "";
                    etBuyAmount.setText(inputString);
                    etBuyAmount.setSelection(0);
                }
                if (inputString.length() == 0) {
                    tvEstimatedGram.setText("0.000");
                    buttonInvalid();
                } else {
                    double inputAmount = Double.parseDouble(inputString.toString().trim());
                    if (inputAmount < 100) {
                        tvEstimatedGram.setText("金额大于等于100元");
                        buttonInvalid();
                    } else {
                        buttonEffective();
                        if (!TextUtils.isEmpty(gold_price)) {
                            double goldPrice = Double.parseDouble(gold_price.toString());
                            tvEstimatedGram.setText(Utils.decimalADivideB(inputAmount, goldPrice));
                        }
                    }
                }
            }
        });
    }


    private void confirmChoose() {
        ActionUtil actionUtil = new ActionUtil(BuyGoldActivity.this);
        actionUtil.confirmChoose(regularId, buyGrams, buyAmount, buyType);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()){
                    return;
                }
                BuyConfirmModel confirmModel = (BuyConfirmModel) model;
                if (confirmModel == null) {
                    UIHelper.showToast(BuyGoldActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (confirmModel.getErrorMsg() != null) {
                    if (confirmModel.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(BuyGoldActivity.this, getString(R.string.crowding_in_tips_txt));
                    } else if (confirmModel.getErrorCode().equals(Strs.TOKEN_EXPIRATION)) {
                        ActivityUtils.forceQuit(BuyGoldActivity.this, getString(R.string.token_expired_tips_txt));
                    } else {
                        UIHelper.showToast(BuyGoldActivity.this, confirmModel.getErrorMsg());
                    }
                } else {
                    Message msg = new Message();
                    msg.what = CONFIRM_CHOOSE_SUCCESS;
                    msg.obj = confirmModel;
                    handle.sendMessage(msg);
                }
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.tv_follow_grams, R.id.tv_follow_amount, R.id.btn_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_follow_grams:
                etBuyAmount.setText("");
                tvFollowGrams.setSelected(true);
                tvFollowAmount.setSelected(false);
                ivAmountLine.setBackgroundColor(getResources().getColor(R.color.color_white));
                ivGramLine.setBackgroundColor(getResources().getColor(R.color.yellow_btn_bg));
                followGramLayout.setVisibility(View.VISIBLE);
                followAmountLayout.setVisibility(View.GONE);
                followAmount = false;
                break;
            case R.id.tv_follow_amount:
                etBuyGram.setText("");
                tvFollowGrams.setSelected(false);
                tvFollowAmount.setSelected(true);
                etBuyAmount.requestFocus();
                ivAmountLine.setBackgroundColor(getResources().getColor(R.color.yellow_btn_bg));
                ivGramLine.setBackgroundColor(getResources().getColor(R.color.color_white));
                followGramLayout.setVisibility(View.GONE);
                followAmountLayout.setVisibility(View.VISIBLE);
                followAmount = true;
                break;
            case R.id.btn_pay:
                if (followAmount) {
                    String inputAmount = etBuyAmount.getText().toString();
                    if (TextUtils.isEmpty(inputAmount)) {
                        UIHelper.showToast(BuyGoldActivity.this, "请输入金额");
                        return;
                    }
                    if (Double.parseDouble(inputAmount) < 100) {
                        UIHelper.showToast(BuyGoldActivity.this, "买金金额不能低于100");
                        return;
                    }
                    buyType = "BY_MONEY";
                    buyAmount = inputAmount;
                    buyGrams = tvEstimatedGram.getText().toString();
                } else {
                    String inputGram = etBuyGram.getText().toString();
                    if (TextUtils.isEmpty(inputGram)) {
                        UIHelper.showToast(BuyGoldActivity.this, "请输入克数");
                        return;
                    }
                    buyType = "BY_GRAM";
                    buyGrams = inputGram;
                    buyAmount = tvEstimatedAmount.getText().toString();
                }
                confirmChoose();
                break;
        }
    }

    private void buttonEffective() {
        btnPay.setBackgroundColor(getResources().getColor(R.color.yellow_btn_bg));
        btnPay.setTextColor(getResources().getColor(R.color.color_gray));
        btnPay.setEnabled(true);
    }

    private void buttonInvalid() {
        btnPay.setEnabled(false);
        btnPay.setBackgroundColor(getResources().getColor(R.color.color_aaaaaa));
        btnPay.setTextColor(getResources().getColor(R.color.color_white));
    }
}
